spring 中 Bean
http://www.voidcn.com/article/p-peghajxt-bpb.html
https://www.awaimai.com/2596.html
https://juejin.im/post/5b1b841de51d4506d47df108
org.springframework.web.bind.annotation
reference: https://www.baeldung.com/spring-mvc-annotations
@Controller: used with @requestMapping
1
2
3
4
5
6
7
8
9
10
11
"books") (
public class SimpleBookController {
"/{id}", produces = "application/json") (
public Book getBook(@PathVariable int id) {
return findBookById(id);
}
private Book findBookById(int id) {
// ...
}
}@RestController==@Controller@ResponseBody: render the result string directly back to the caller
serialize the return objects into http response
1
2
3
4
5
6
7
8
9
10
11
"books-rest") (
public class SimpleBookRestController {
"/{id}", produces = "application/json") (
public Book getBook(@PathVariable int id) {
return findBookById(id);
}
private Book findBookById(int id) {
// ...
}
}@RequestMapping: map specific http requests to specific method
1
2
3
4
5
6
7
class VehicleController {
"/vehicles/home", method = RequestMethod.GET) (value =
String home() {
return "home";
}
}- path
- method
- params
- headers
- consumes
- produces(media type that can be produced)
- @Getmapping
- @Postmapping
- @PutMapping
- @DeleteMapping
- @PatchMappinge
@ResponseBody: 直接将返回的对象输出到客户端,如果是字符串,则直接返回;否则spring-boot默认使用jackson serialize 成 json字符串
@RequestBody: Controller方法带有@RequestBody注解的参数,意味着request 内容是json, spring-boot默认使用jackson deserialize
maps the body of the Http request to an object automatically
1
2
3
4"/save") (
void saveVehicle(@RequestBody Vehicle vehicle) {
// ...
}@ModelAttribute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class EmployeeController {
private Map<Long, Employee> employeeMap = new HashMap<>();
"/addEmployee", method = RequestMethod.POST) (value =
public String submit(
@ModelAttribute("employee") Employee employee,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
public void addAttributes(Model model) {
model.addAttribute("msg", "Welcome to the Netherlands!");
}
}@EnableAutoConfiguration
@RequestParam
1
2
3
4"/buy") (
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
// ...
}@PathVariable
1
2
3
4"/{id}") (
Vehicle getVehicle(@PathVariable("id") long id) {
// ...
}@CookieValue
@RequestHeader
@ResponseBody:treats the return of the method as the response itself
Other Annotations
- @Autowired
- reference:
- @Data